package cn.wolfcode.trip.app.webSocket;

import cn.wolfcode.trip.base.util.SpringBeanFactoryUtils;
import cn.wolfcode.trip.base.domain.UserMessage;
import cn.wolfcode.trip.base.service.ILetterService;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;


@ServerEndpoint("/socket/letter")
public class MessageSocket {
    //因为该类我目前无法把它交给spring管理,只能手动注入依赖
    //手动注入Bean的代码
    private ILetterService letterService;
    {
        letterService = (ILetterService) SpringBeanFactoryUtils.getBeanById("LetterServiceImpl");
    }
   /* {
        try {
            String[] confFile = {"applicationContext.xml"};
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(confFile);
            letterService = (ILetterService) context.getBean("LetterServiceImpl");
            System.out.println("############################");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/


    //在连接中的所有客户端会话
    private static final Set<MessageSocket> users = new CopyOnWriteArraySet<>();
    //和某一个客户端建立的连接会话
    Session session;
    //保存对方的信息,保证当前的对话是一对一的;
    private Map map = new HashMap();
    //建立连接
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        //users.add(this);
        System.out.println("建立连接");
    }

    //断开连接
    @OnClose
    public void onClose() {
        System.out.println("断开连接");
        users.remove(this);
    }

    //客户端传来的信息
    @OnMessage
    public void onMessage(String msg) throws Exception{
        System.out.println("收到信息");
        System.out.println(msg);
        //判断是否是敲门信息
        if (msg.startsWith("###&")){
            initSession(msg);
        }else {
            saveMsg(msg);
            backMsg(msg);
        }
    }

    private void saveMsg(String msg) {
        String[] strings = msg.split("&");
        UserMessage message = new UserMessage();
        message.setUser1Id(Long.valueOf(strings[1]));
        message.setUser2Id(Long.valueOf(strings[2]));
        message.setTime(new Date());
        message.setMsg(msg);
        letterService.save(message);
    }

    private void initSession(String msg) throws Exception{
        String[] strings = msg.split("&");
        map.put(strings[1],strings[1]);
        map.put(strings[2],strings[2]);
        users.add(this);
        List<UserMessage> list = letterService.selectOldMessage(strings[1], strings[2]);
        for (UserMessage userMessage : list) {
            session.getBasicRemote().sendText(userMessage.getMsg() + "&" + formatTime(userMessage.getTime()));
        }
        //标为已读
        letterService.clean(strings[1],strings[2]);
    }
    private String formatTime(Date date){
        SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");
        String time = format.format(date);
        return time;
    }
    //返回信息的方法
    private void backMsg(String msg){
        //client.session.getBasicRemote().sendText(msg1);
        //session.getBasicRemote().sendText(msg);
        msg = msg + "&" + formatTime(new Date());

        //截取发送者的id
        String[] strings = msg.split("&");
        //发送消息提醒
        ListenSocket.push(Long.valueOf(strings[1]),Long.valueOf(strings[2]));
        for (MessageSocket user : users) { //遍历当前连接的用户
            //存有当前双方id的用户返回消息
            if(user.map.get(strings[1]) != null && user.map.get(strings[2]) != null ) {
                try {
                    synchronized (user) {
                        // 向每个用户发送返回消息
                        user.session.getBasicRemote().sendText(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
